<?php
/**
 * 图片类
 * User: ws
 * Date: 2018/7/21
 * Time: 9:27
 */

namespace app\admin\controller;
use think\Db;
use app\admin\model\Image as ImageModel;
class Image extends Init
{
    function index(){
        if ($this->request->isAjax()) {
            $list = ImageModel::order('image_id desc')->paginate(input('limit'))->toArray();
            $imag_url = config('aliyun_oss.url');

            foreach ($list['data'] as $key=>$itme){
                $list['data'][$key]['img'] = str_replace("/ad",$imag_url."ad",$itme['img']);
            }
            return json($result = ['code'=>0,'msg'=>'获取成功','data'=>$list['data'],'count'=>$list['total']]);
        }
        return view('list');
    }


    function add(){
        if(request()->isPost()){
            $data = $this->request->post();
            if(empty($data['img'])){
                return json(array('code'=>0,'msg'=>'添加失败，请上传图片'));
            }

            if($data['type']==1){
                if(empty($data['url'])){
                    return json(array('code'=>0,'msg'=>'添加失败，地址不能为空'));
                }
            }elseif($data['type']==0){
                $data['url'] = $data['usr'];
            }elseif($data['type']==-1){
                return json(array('code'=>0,'msg'=>'添加失败，请选择商品类型'));
            }
            unset($data['usr']);

            if($data['type']==2){
                $data['url']==0;
            }

            if (!ImageModel::create($data)) {
                return json(array('code'=>0,'msg'=>'添加失败'));
            }
            return json(array('code'=>200,'msg'=>'添加成功'));
        }
        $goods = Db::name('goods')->field('goods_id,name')->select();
        return view('add',['goods'=>$goods]);
    }

    function edit(){
        if(request()->isPost()){
            $data = $this->request->post();
            if($data['type']==1){
                if(empty($data['url'])){
                    return json(array('code'=>0,'msg'=>'更新失败，地址不能为空'));
                }
            }else{
                $data['url'] = $data['usr'];
            }
            unset($data['usr']);
            if($data['type']==2){
                $data['url']==0;
            }
            if (!ImageModel::update($data)) {
                return json(array('code'=>0,'msg'=>'更新失败'));
            }
            return json(array('code'=>200,'msg'=>'更新成功'));
        }

        $list = ImageModel::where('image_id', input('id'))->find()->toArray();
        $imag_url = config('aliyun_oss.url');
        $list['img'] = str_replace("/ad",$imag_url."ad",$list['img']);
        $goods = Db::name('goods')->field('goods_id,name')->select();
        return view('edit',['list'=>$list,'goods'=>$goods]);
    }


    function del(){
        $id = input('id');
        if (!ImageModel::destroy(['image_id' => $id])) {
            return json(array('code'=>0,'msg'=>'删除失败'));
        }
        return json(array('code'=>200,'msg'=>'删除成功'));
    }
}